package com.demo.order.service;

import com.alibaba.fastjson.JSON;
import com.demo.order.entity.SeckillOrder;
import com.demo.order.feign.ProductFeignClient;
import com.demo.order.mapper.SeckillOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 秒杀订单服务类
 * 处理订单创建、支付、取消等业务逻辑
 */
@Slf4j
@Service
public class SeckillOrderService {

    @Autowired
    private SeckillOrderMapper seckillOrderMapper;

    @Autowired
    private ProductFeignClient productFeignClient;

    /**
     * 创建秒杀订单
     * @param userId 用户ID
     * @param productId 商品ID
     * @param quantity 购买数量
     * @param messageId 消息ID（用于幂等性控制）
     * @return 订单创建结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> createSeckillOrder(Long userId, Long productId, Integer quantity, String messageId) {
        log.info("开始创建秒杀订单，userId: {}, productId: {}, quantity: {}, messageId: {}", 
                userId, productId, quantity, messageId);

        try {
            // 1. 幂等性检查
            if (StringUtils.hasText(messageId)) {
                SeckillOrder existOrder = seckillOrderMapper.selectByMessageId(messageId);
                if (existOrder != null) {
                    log.info("订单已存在，messageId: {}, orderId: {}", messageId, existOrder.getOrderId());
                    return createSuccessResult(existOrder);
                }
            }

            // 2. 获取商品信息
            Map<String, Object> productInfo = productFeignClient.getProductInfo(productId);
            if (!(Boolean) productInfo.get("success")) {
                log.error("获取商品信息失败，productId: {}", productId);
                return createErrorResult("获取商品信息失败");
            }

            // 3. 扣减库存
            Map<String, Object> reduceResult = productFeignClient.reduceStock(productId, quantity);
            if (!(Boolean) reduceResult.get("success")) {
                log.error("扣减库存失败，productId: {}, quantity: {}", productId, quantity);
                return createErrorResult("库存不足或扣减失败");
            }

            // 4. 创建订单
            SeckillOrder order = new SeckillOrder();
            order.setUserId(userId);
            order.setProductId(productId);
            order.setProductName((String) productInfo.get("productName"));
            order.setQuantity(quantity);
            order.setPrice(new BigDecimal(productInfo.get("price").toString()));
            order.setTotalAmount(order.getPrice().multiply(new BigDecimal(quantity)));
            order.setStatus(SeckillOrder.STATUS_PENDING);
            order.setExpireTime(LocalDateTime.now().plusMinutes(30)); // 30分钟后过期
            order.setCreateTime(LocalDateTime.now());
            order.setUpdateTime(LocalDateTime.now());
            order.setMessageId(messageId != null ? messageId : UUID.randomUUID().toString());

            int insertResult = seckillOrderMapper.insert(order);
            if (insertResult > 0) {
                log.info("秒杀订单创建成功，orderId: {}", order.getOrderId());
                return createSuccessResult(order);
            } else {
                // 订单创建失败，回滚库存
                productFeignClient.rollbackStock(productId, quantity);
                log.error("订单创建失败，已回滚库存");
                return createErrorResult("订单创建失败");
            }

        } catch (Exception e) {
            log.error("创建秒杀订单异常", e);
            // 异常情况下尝试回滚库存
            try {
                productFeignClient.rollbackStock(productId, quantity);
            } catch (Exception rollbackException) {
                log.error("回滚库存异常", rollbackException);
            }
            return createErrorResult("系统异常，请稍后重试");
        }
    }

    /**
     * 支付订单
     * @param orderId 订单ID
     * @return 支付结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> payOrder(Long orderId) {
        log.info("开始支付订单，orderId: {}", orderId);

        try {
            SeckillOrder order = seckillOrderMapper.selectById(orderId);
            if (order == null) {
                return createErrorResult("订单不存在");
            }

            if (order.getStatus() != SeckillOrder.STATUS_PENDING) {
                return createErrorResult("订单状态异常，无法支付");
            }

            if (order.getExpireTime().isBefore(LocalDateTime.now())) {
                return createErrorResult("订单已过期");
            }

            // 更新订单状态为已支付
            int updateResult = seckillOrderMapper.updatePayStatus(orderId, LocalDateTime.now());
            if (updateResult > 0) {
                log.info("订单支付成功，orderId: {}", orderId);
                return createSuccessResult("支付成功");
            } else {
                return createErrorResult("支付失败");
            }

        } catch (Exception e) {
            log.error("支付订单异常，orderId: {}", orderId, e);
            return createErrorResult("系统异常，请稍后重试");
        }
    }

    /**
     * 取消超时订单
     * @return 取消结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> cancelExpiredOrders() {
        log.info("开始取消超时订单");

        try {
            List<SeckillOrder> expiredOrders = seckillOrderMapper.selectExpiredOrders(LocalDateTime.now());
            if (expiredOrders.isEmpty()) {
                return createSuccessResult("没有超时订单需要取消");
            }

            List<Long> orderIds = expiredOrders.stream()
                    .map(SeckillOrder::getOrderId)
                    .toList();

            // 批量取消订单
            int cancelCount = seckillOrderMapper.batchCancelOrders(orderIds);

            // 回滚库存
            for (SeckillOrder order : expiredOrders) {
                try {
                    productFeignClient.rollbackStock(order.getProductId(), order.getQuantity());
                } catch (Exception e) {
                    log.error("回滚库存失败，orderId: {}, productId: {}, quantity: {}", 
                            order.getOrderId(), order.getProductId(), order.getQuantity(), e);
                }
            }

            log.info("取消超时订单完成，取消数量: {}", cancelCount);
            return createSuccessResult("取消超时订单: " + cancelCount + " 个");

        } catch (Exception e) {
            log.error("取消超时订单异常", e);
            return createErrorResult("系统异常");
        }
    }

    /**
     * 根据用户ID和商品ID查询订单
     * @param userId 用户ID
     * @param productId 商品ID
     * @return 订单列表
     */
    public List<SeckillOrder> getOrdersByUserAndProduct(Long userId, Long productId) {
        return seckillOrderMapper.selectByUserAndProduct(userId, productId);
    }

    /**
     * 根据订单ID查询订单
     * @param orderId 订单ID
     * @return 订单信息
     */
    public SeckillOrder getOrderById(Long orderId) {
        return seckillOrderMapper.selectById(orderId);
    }

    /**
     * 创建成功响应
     */
    private Map<String, Object> createSuccessResult(Object data) {
        return Map.of(
                "success", true,
                "message", "操作成功",
                "data", data
        );
    }

    /**
     * 创建成功响应
     */
    private Map<String, Object> createSuccessResult(String message) {
        return Map.of(
                "success", true,
                "message", message
        );
    }

    /**
     * 创建错误响应
     */
    private Map<String, Object> createErrorResult(String message) {
        return Map.of(
                "success", false,
                "message", message
        );
    }
}